package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    private VideoService videoService;

    @DubboReference
    private UserInfoService userInfoService;

    // 推荐视频查询
    public ResponseEntity findVideoVoByPage(Integer pageNum, Integer pageSize) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询推荐视频分页对象
        PageBeanVo pageBeanVo = videoService.findVideoByPage(userId, pageNum, pageSize);
        // 3.将voList设置到分页对象
        // 3-1 声明voList
        List<VideoVo> voList = new ArrayList<>();
        // 3-2 获取videoList
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        // 3-3 遍历
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                // 创建vo
                VideoVo vo = new VideoVo();
                // 先userInfo
                vo.setUserInfo(userInfoService.findById(video.getUserId()));
                // 后video
                vo.setVideo(video);

                // 判断我是否关注了视频作者
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER, userId, video.getUserId()))) {
                    vo.setHasFocus(1);
                }

                // 添加到voList
                voList.add(vo);
            }
        }
        // 4.设置到分页对象
        pageBeanVo.setItems(voList);

        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    // 发布动态
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2 .上传封面
        StorePath storePath1 = client.uploadFile(videoThumbnail.getInputStream() // 文件io流
                , videoThumbnail.getSize() // 文件大小
                , FileUtil.extName(videoThumbnail.getOriginalFilename()) // 文件扩展名
                , null);//  文件元属性
        String picUrl = webServer.getWebServerUrl() + storePath1.getFullPath();
        // 3.上传视频
        StorePath storePath2 = client.uploadFile(videoFile.getInputStream()
                , videoFile.getSize()
                , FileUtil.extName(videoFile.getOriginalFilename())
                , null);
        String videoUrl = webServer.getWebServerUrl() + storePath2.getFullPath();
        // 4.封装video对象
        Video video = new Video();
        video.setId(ObjectId.get()); // 视频主键
        video.setCreated(System.currentTimeMillis());// 发布时间
        video.setUserId(userId);// 视频发布人
        video.setText("小鸡炖蘑菇"); // 视频文字
        video.setPicUrl(picUrl);// 视频封面
        video.setVideoUrl(videoUrl); // 视频内容
        // 5.调用rpc保存
        videoService.saveVideo(video);
    }

    @DubboReference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 关注
    public void saveUserFocus(Long focusUserId) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.封装对象
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis());
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);
        // 3.调用rpc保存
        focusUserService.saveFocusUser(focusUser);
        // 4.redis存储关注标记     focus_user:99_1  = 1
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");
    }

    // 取消关注
    public void userUnFocus(Long focusUserId) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc删除
        focusUserService.removeFocusUser(userId, focusUserId);
        // 3 .redis移除关注标记
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));
    }
}
